//巡店
<template>
  <view class="page_wraper">
    <view class="left_container" v-if="currentTask">
      <view class="progress_container">
        <view class="row_container_center">
          <view class="progress_text">{{percentText}}</view>
          <view class="progress_title">进度</view>
        </view>
        <uv-line-progress :percentage="percentage" activeColor="#54B9CC" />
      </view>
      <view v-if="taskList.length>0" class="task_item" :data-selected="item.selected" v-for="(item,index) in taskList"
        :key="index" @click="taskClick(index,item)">
        {{item.modelTaskName}}
      </view>
      <view class="add_bg" @click="ceateTask">
        <image class="add_img" src="../../static/inspection/icon_add.png"></image>
      </view>
    </view>

    <view class="right_container" v-if="currentTask">
      <view class="task_header_container">
        <view>
          <view class="qualified">{{currentTask.qualified||0}}</view>
          <view class="progress_title">合格</view>
        </view>
        <view>
          <view class="not_qualified">{{currentTask.unqualified||0}}</view>
          <view class="progress_title">不合格</view>
        </view>
        <view>
          <view class="rectification">{{currentTask.inapplicability||0}}</view>
          <view class="progress_title">不适用</view>
        </view>
        <view class="detail_task_progress">
          <view class="detail_task_qualified">{{currentTask.qualified||0}}</view>
          <view class="detail_task_total">{{'/'+currentTask.totalItem}}</view>
        </view>
      </view>

      <view v-if="taskList.length>0">
        <!-- <view class="row_container">
          <image class="icon" src="../../static/inspection/icon_task_item.png"></image>
          <view class="detail_task_title">{{currentTask.modelTaskName}}</view>
        </view> -->
        <view v-for="(item,index) in currentTask.modelTaskPatrolDomains" :key="index">
          <view v-if="index === 0 || item.classifyName !== currentTask.modelTaskPatrolDomains[index - 1].classifyName"
            class="row_container">
            <!-- <image class="icon" src="../../static/inspection/icon_task_item.png"></image> -->
            <view class="detail_task_title">{{item.classifyName}}</view>
          </view>
          <view class="card">

            <view class="row_container_space">
              <view class="detail_item_task_title">{{item.checkitemName}}</view>
            </view>
            <view class="row_container_space">
              <view class="score_total">{{'分值：'+item.score}}</view>
              <view class="score">{{getResultScore(item)}}</view>
            </view>
            <view class="text_container">
              <textarea class="text_area" v-model="item.checkDescription" placeholder="写点什么"
                :disabled="item.dataState>=30" placeholder-style="font-size:30rpx"></textarea>
            </view>
            <view v-if="item.excuteImgList.length>0" class="container_upload_img">
              <view class="item_upload_view" v-for="(imageItem, imageIndex) in item.excuteImgList" :key="imageIndex">
                <image class="item_upload_img_large"
                  :src="imageItem.isAdd?'../../static/inspection/icon_camera.png':imageItem.url"
                  @click="tagClick(imageItem,item.excuteImgList,index)">
                </image>

              </view>
            </view>
            <view v-if="item.isPic ==1" class="container_upload_img">
              <view class="item_upload_view" v-for="(imageItem, imageIndex) in item.imgList" :key="imageIndex">
                <image class="item_upload_img"
                  :src="imageItem.isAdd?'../../static/inspection/icon_camera.png':'../../static/inspection/icon_img.png'"
                  @click="tagClick(imageItem,item.imgList,index)">
                </image>

              </view>
            </view>
            <view class="button_container" v-if="item.dataState<30">
              <button class="button" @click="updateTaskPatrol(1,item)">
                合格
              </button>
              <button class="button" @click="updateTaskPatrol(2,item)">
                不合格
              </button>
              <button class="button" @click="updateTaskPatrol(3,item)">不适用</button>
            </view>
          </view>
        </view>
        <view class="row_container">
          <view class="detail_task_title">巡店总结</view>
        </view>
        <view class="card">
          <view class="text_container_summary">
            <textarea class="text_area_summary" v-model="currentTask.summary" placeholder="写点什么"
              placeholder-style="font-size:30rpx"></textarea>
          </view>

          <view class="button_container">
            <button class="button_summary">
              查看
            </button>
            <button class="button_summary_submit" @click="submit">
              提交
            </button>
          </view>
        </view>
      </view>
    </view>

    <view class="nodata" v-if="!currentTask">
      <image class="no_data_img" src="../../static/images/blank_large.png"></image>
      <!-- <text class="no_data_text">暂无数据</text> -->
      <button class="button_normal" @click="ceateTask">新建巡店</button>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { onLoad, onUnload } from '@dcloudio/uni-app';
  import { queryClModelTaskMap, updateModelTaskPatrol, updateClModelTaskSelective } from '@/services/inspection'
  import { uploadFilePromise } from '@/utils/upload';
  import { useMemberStore } from '@/stores';
  import { useReturnStore } from '@/stores/modules/returnStore';
  import Func from '@/utils/func';

  const userInfo = useMemberStore().getUserInfo()
  //当前任务的百分比
  const percentage = ref(10)

  const percentText = ref('')
  //任务列表
  const taskList = ref<any[]>([])
  //当前任务
  const currentTask = ref<any>(null)
  let data : any = {}
  //页面传参
  const query = defineProps<{
    data : string
  }>()

  //页面初始化
  onLoad(() => {
    //监听水印相机拍照结果
    uni.$on('wahterRemark', (result : any) => {
      console.log(result)
      console.log(currentIndex.value)
      console.log(currentTask.value.modelTaskPatrolDomains[currentIndex.value])
      currentTask.value.modelTaskPatrolDomains[currentIndex.value].imgList.splice(0, 0, {
        url: result.url,
        id: result.fileId,
        isAdd: false
      })
    })
    //监听新建任务 刷新页面
    uni.$on('ceateTask', () => {
      getTaskData()
    })
    console.log(query.data)
    data = JSON.parse(query.data)
    //页面标题为门店名
    uni.setNavigationBarTitle({
      title: data.name
    })
    getTaskData()


  })
  onUnload(() => {
    uni.$off('createTask')
    uni.$off('wahterRemark')
  })
  //当前得分
  const getResultScore = (item : any) => {
    let score = 0
    if (currentTask.value.scoreRule == 1) {
      //合格得分
      score = (item.results == 1 || item.results == 3) ? (item.score + item.rpScore) : 0
      return '得分：' + score
    }
    //不合格减分
    score = (item.results == 2) ? -(item.rpScore) : 0
    return '扣分：' + score


  }
  /**
   *
   */
  const getTaskData = () => {
    queryClModelTaskMap({ shopCode: data.code }).then((res : any) => {
      //任务进度
      percentText.value = `${res.completeTask}/${res.totalTask}`
      percentage.value = res.completeTask / res.totalTask
      if (res.clModelTaskReDomains) {
        const domains = JSON.parse(res.clModelTaskReDomains)
        taskList.value = []
        domains.forEach((item : any, index : number) => {
          //设置当前第一项为选中项
          if (index == 0) {
            item.selected = 1
          }
          //点检项列表
          item.modelTaskPatrolDomains.forEach((patrol : any) => {

            patrol.imgList = []
            //检查附件连接解析
            if (patrol.checkAttachUrl) {
              if (patrol.checkAttachUrl.includes(',')) {

                patrol.checkAttachUrl.split(',').forEach((url : any, index : number) => {
                  patrol.imgList.push({
                    url,
                    id: '',
                    isAdd: false
                  })
                })
              } else {
                patrol.imgList.push({
                  url: patrol.checkAttachUrl,
                  id: '',
                  isAdd: false
                })
              }

            }
            patrol.excuteImgList = []
            //执行附件
            if (patrol.executeAttachUrl) {
              if (patrol.executeAttachUrl.includes(',')) {

                patrol.executeAttachUrl.split(',').forEach((url : any, index : number) => {
                  patrol.excuteImgList.push({
                    url,
                    id: '',
                    isAdd: false
                  })
                })
              } else {
                patrol.excuteImgList.push({
                  url: patrol.executeAttachUrl,
                  id: '',
                  isAdd: false
                })
              }

            }
            //点检项 已完成 30
            if (patrol.dataState < 30) {
              //添加项放最后
              const add = {
                url: '',
                id: '',
                isAdd: true
              }
              patrol.imgList.push(add)
            }

          })
          taskList.value.push(item)
        })
        console.log('taskList', taskList.value)
        //当前的任务
        currentTask.value = taskList.value[0]
      }
    })
  }
  //左侧点击事件
  const taskClick = (currentIndex : number, currentItem : any) => {
    taskList.value.forEach((item, index) => {
      if (currentIndex == index) {
        item.selected = 1
      } else {
        item.selected = 0
      }
    })
    //当前的任务
    currentTask.value = taskList.value[currentIndex]
  }
  /**
   * @results 1.合格 2.不合格 3.不适用
   */
  const updateTaskPatrol = (results : number, item : any) => {

    console.log(item)

    const newUrlList = item.imgList.splice(0, item.imgList.length - 1)
    //链接转化
    const checkAttachUrl = newUrlList.map((item : any) => item.url).join(',')
    console.log(checkAttachUrl)
    uni.showLoading({
      title: ''
    })
    updateModelTaskPatrol({
      modelTaskPatrolId: item.modelTaskPatrolId,
      results,
      checkUser: userInfo?.userCode,
      checkAttachUrl,
      checkUsername: userInfo?.userRelname,
      checkDescription: item.checkDescription || ''
    }).then((res : any) => {
      uni.hideLoading()
      if (res.success) {
        getTaskData()
        uni.showToast({
          title: '更新成功',
          icon: 'none'
        })
      }
    })
  }
  const submit = () => {
    if (Func.isEmpty(currentTask.value.summary)) {
      uni.showToast({
        title: '请先填写巡店总结',
        icon: 'none'
      })
      return
    }
    uni.showLoading({
      title: ''
    })
    updateClModelTaskSelective({
      modelTaskId: currentTask.value.modelTaskId,
      summary: currentTask.value.summary,
      checkTime: new Date().toISOString().replace('T', ' ').replace(/\..+/, '')

    }).then((res : any) => {
      uni.hideLoading()
      if (res.success) {
        uni.showToast({
          title: '提交成功',
          icon: 'none'
        })
      }
    })
  }
  //删除
  const deleteItem = (imagesList : any, index : number) => {
    imagesList.splice(index, 1);
  }
  //当前点击 项index
  const currentIndex = ref(0)
  //列表展示
  const tagClick = (item : any, images : any, index : number) => {
    console.log(item)
    if (item.isAdd) {
      //记录当前项
      currentIndex.value = index
      uni.navigateTo({
        url: '/pages/camera/waterremark'
      })
      // uni.chooseImage({
      //   count: 1,
      //   secret: false,
      //   position: 'back',
      //   sourceType: ['camera', 'album'],
      //   success: (res : any) => {
      //     console.log('选择的文件列表:', res.tempFiles[0].path);
      //     // res.tempFiles 结构： [{ path: '临时路径', name: '文件名', size: 文件大小, type: '文件类型' }]
      //     uploadFilePromise(res.tempFiles[0].path).then((result : any) => {
      //       console.log(result)
      //       images.splice(0, 0, {
      //         url: result.url,
      //         id: result.fileId,
      //         isAdd: false
      //       })
      //     })
      //   },
      //   fail: () => { },
      //   complete: () => { },
      // });
    } else {
      var urls = []
      urls.push(item.url)
      uni.previewImage({
        urls: urls,
        current: 0,
        success: () => { },
        fail: () => { },
        complete: () => { },
      });
    }
  }

  //创建任务 选择模版
  const ceateTask = () => {
    uni.navigateTo({
      url: `/pagesMember/inspection/templatetasks?data=${JSON.stringify({
        ...data
      })}`
    })
  }
</script>


<style>
  page {
    background-color: white;
  }

  .page_wraper {
    display: flex;
    flex-direction: row;
    padding: 15rpx 15rpx;
  }

  .left_container {
    width: 28vw;
    margin-right: 16rpx;
  }

  .right_container {
    width: 72vw;
    padding-bottom: 20rpx;
  }

  .progress_container {
    background: rgba(179, 220, 246, 0.1);
    padding: 16rpx;
    justify-content: center;
    display: flex;

  }

  .progress_text {
    height: 52rpx;
    font-size: 36rpx;
    color: #1C253A;
    font-weight: bold;
    line-height: 52rpx;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }

  .detail_task_total {

    height: 44rpx;
    font-size: 32rpx;
    color: #555;
    line-height: 44rpx;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }

  .progress_title {
    height: 44rpx;
    font-size: 28rpx;
    color: #555;
    line-height: 44rpx;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }

  .add_bg {
    margin-top: 15rpx;
    border: 3rpx dashed #54B9CC;
    display: flex;
    border-radius: 6rpx;
  }

  .add_img {
    margin: 20rpx auto;
    height: 50rpx;
    width: 50rpx
  }

  .task_item {
    background-color: #F9FAFB;
    padding: 30rpx 15rpx;
    font-size: 28rpx;
    margin-top: 5rpx;
    color: #888E98;
    text-align: left;
    font-style: normal;
    text-transform: none;
    overflow: hidden;
    border-radius: 6rpx;
  }

  .icon {
    height: 64rpx;
    width: 64rpx;
  }

  .task_item[data-selected='1'] {
    background-color: #54B9CC;
    color: white;
  }

  .task_header_container {
    background: rgba(179, 220, 246, 0.1);
    padding: 16rpx;
    margin-bottom: 24rpx;
    justify-content: space-around;
    display: flex;
    flex-direction: row;
  }

  .qualified {
    height: 52rpx;
    font-size: 36rpx;
    color: #54B9CC;
    font-weight: bold;
    line-height: 52rpx;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }

  .not_qualified {
    height: 52rpx;
    font-size: 36rpx;
    color: #858389;
    font-weight: bold;
    line-height: 52rpx;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }

  .rectification {
    height: 52rpx;
    font-size: 36rpx;
    color: #E02020;
    font-weight: bold;
    line-height: 52rpx;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }

  .detail_task_progress {
    display: flex;
    flex-direction: row;
    color: #394259;
    font-size: 30rpx;
    align-items: center;
    justify-content: center;
  }

  .detail_task_qualified {
    color: #54B9CC;
    font-size: 32rpx;
  }

  .detail_task_title {
    font-weight: bold;
    font-size: 32rpx;
    line-height: 64rpx;
    height: 64rpx;
    margin-left: 12rpx;
    color: black;
    text-align: left;
    vertical-align: center;
    font-style: normal;
    text-transform: none;
  }

  .card {
    width: 98%;
    margin-top: 16rpx;
    margin-left: 15rpx;
    padding: 10rpx;
    background: #FFFFFF;
    box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(209, 227, 230, 0.58);
    border-radius: 16rpx 16rpx 16rpx 16rpx;
  }

  .detail_item_task_title {

    font-size: 30rpx;
    color: #1C253A;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .row_container {
    margin-top: 16rpx;
    display: flex;
    flex-direction: row;
  }

  .row_container_center {
    margin-top: 16rpx;
    display: flex;
    flex-direction: row;
    justify-content: center;
  }

  .row_container_space {
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 16rpx 10rpx;
    justify-content: space-between;
  }

  .score {
    height: 40rpx;
    font-size: 30rpx;
    margin-left: 16rpx;
    color: #54B9CC;
    line-height: 40rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .score_total {
    height: 40rpx;
    font-size: 30rpx;
    color: #888E98;
    line-height: 40rpx;
    text-align: left;
    font-style: normal;
    text-transform: none;
  }

  .text_container_summary {
    background: #FFFFFF;
    height: 200rpx;
    margin: 16rpx;
    padding: 16rpx;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    border: 1rpx solid #f5f6f5;
  }

  .text_area_summary {
    height: 200rpx;
    width: 100%;
  }

  .text_container {
    background: #FFFFFF;
    height: 120rpx;
    margin: 16rpx;
    padding: 16rpx;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    border: 1rpx solid #f5f6f5;
  }

  .text_area {
    width: 100%;
    height: 120rpx;
  }

  .button_container {
    display: flex;
    margin-top: 20rpx;
    margin-bottom: 20rpx;
    flex-direction: row;
    gap: 14rpx;
    justify-content: space-around;
  }

  .button {
    width: 28%;
    color: #54B9CC;
    height: 64rpx;
    line-height: 64rpx;
    font-size: 30rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 2rpx solid #54B9CC;
  }

  .button_summary {
    width: 40%;
    color: #54B9CC;
    height: 64rpx;
    line-height: 64rpx;
    font-size: 30rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 2rpx solid #54B9CC;
  }

  .button_summary_submit {
    width: 40%;
    color: white;
    height: 64rpx;
    line-height: 64rpx;
    font-size: 30rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    background-color: #54B9CC;
  }

  .container_upload_img {
    width: 93vw;
    display: flex;
    margin-left: 20rpx;
    margin-top: 10rpx;
    row-gap: 15rpx;
    column-gap: 12rpx;
    flex-wrap: wrap;


  }

  .item_upload_img_large {
    width: 176rpx;
    height: 176rpx;
    font-size: 28upx;
    color: #1685fb;
    text-decoration: underline
  }

  .item_upload_view {
    position: relative;
    display: flex;
    margin: 10rpx 5rpx;
    align-items: flex-end;
  }

  .item_delete {
    position: absolute;
    right: 2rpx;
    top: 2rpx;
    z-index: 100;
    width: 40rpx;
    height: 40rpx;
  }

  .item_upload_img {
    width: 84rpx;
    height: 84rpx;
    font-size: 28upx;
    color: #1685fb;
    text-decoration: underline
  }

  .nodata {
    display: flex;
    height: 80vh;
    width: 100vw;
    margin: auto;
    align-items: center;
    flex-direction: column;

  }

  .no_data_img {
    margin-top: 25vh;
    height: 342rpx;
    width: 320rpx;
  }

  .button_normal {
    width: fit-content;
    margin-top: -50rpx;
    padding: 0rpx 45rpx;
    color: #54B9CC;
    font-size: 28rpx;
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    border: 2rpx solid #54B9CC;
  }

  .no_data_text {
    margin-top: 30rpx;
    color: darkgray;
  }
</style>
